package com.wh.wisdomsite.xbox.st.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.wh.wisdomsite.xbox.common.reponse.CommonResult;
import com.wh.wisdomsite.xbox.core.XboxException;
import com.wh.wisdomsite.xbox.pojo.st.PurchaseDetailIn;
import com.wh.wisdomsite.xbox.st.dao.ContractDetailMapper;
import com.wh.wisdomsite.xbox.st.dao.PurchaseDetailMapper;
import com.wh.wisdomsite.xbox.st.entity.ContractDetail;
import com.wh.wisdomsite.xbox.st.entity.Material;
import com.wh.wisdomsite.xbox.st.entity.PurchaseApply;
import com.wh.wisdomsite.xbox.st.entity.PurchaseDetail;
import com.wh.wisdomsite.xbox.st.service.IMaterialService;
import com.wh.wisdomsite.xbox.st.service.IPurchaseDetailService;
import com.wh.wisdomsite.xbox.st.service.IStoreService;
import com.wh.wisdomsite.xbox.us.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 采购申请清单serviceImpl
 * @version V1.0
 * @author: 杨世强
 * @Package com.wh.wisdomsite.xbox.st.service.impl
 * @date 2018-12-24 14:43
 * @Copyright 企业版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@Service("purchaseDetailService")
@Transactional(rollbackFor = {Exception.class,RuntimeException.class})
public class PurchaseDetailServiceImpl extends ServiceImpl<PurchaseDetailMapper,PurchaseDetail> implements IPurchaseDetailService {
    private static final Log logger = LogFactory.getLog(PurchaseDetailServiceImpl.class);
    @Autowired
    private PurchaseDetailMapper purchaseDetailMapper;

    @Autowired
    private ContractDetailMapper contractDetailMapper;

    @Autowired
    private IMaterialService iMaterialService;

    @Autowired
    private IStoreService iStoreService;


    @Override
    public Page<Map<String, Object>> getContrastPage(Page page, Wrapper<PurchaseDetail> wrapper) {
        SqlHelper.fillWrapper(page, wrapper);
        page.setRecords(this.baseMapper.getContrastPage(page, wrapper));
        return page;
    }

    @Override
    public CommonResult saveOrUpdate(PurchaseApply purchaseApply, List<PurchaseDetail> detailList, User curUser) throws XboxException {
        CommonResult commonResult = new CommonResult();
        for(int i = 0; i < detailList.size(); i++){
            PurchaseDetail purchaseDetail = detailList.get(i);
            //初始的清单物料
            Material material = new Material();
            //判断合同内外
            if(purchaseApply.getPurType().equals("1")){
                //若是合同内，需要判断是否是有对应的合同清单项
                //获取物料
                material = iMaterialService.getMaterial(purchaseDetail.getMaterial());
                if(material == null){
                    throw new XboxException("发生错误，并未存在第"+(i+1)+"行数据的物料信息");
                }
                //根据coId和maId查询
                EntityWrapper<ContractDetail> ew = new EntityWrapper<>();
                ew.setEntity(new ContractDetail());
                ew.eq("cd.coId", purchaseApply.getCoId());
                ew.eq("cd.maId", material.getMaId());
                List<ContractDetail> contractDetailList = contractDetailMapper.selectList(ew);
                if(contractDetailList.size() != 1){
                    throw new XboxException("发生错误，该合同内并未存在第"+(i+1)+"行数据的合同清单项");
                }
                //验证均通过开始添加或更新此条采购清单
            }else {
                //若是合同外，则走类似于合同清单添加的步骤
                //先获取物料ID
                String maId = iMaterialService.getMaId(purchaseDetail.getMaterial());
                if(maId == null){
                    throw new XboxException("获取物料ID发生异常");
                }
                //设置物料的ID
                material.setMaId(maId);
            }
            //判断是添加一条新纪录还是更新原有记录
            if(StringUtils.isEmpty(purchaseDetail.getPurdId())){
                //添加操作
                //先根据purId和maId查找是否已存在此条记录
                EntityWrapper<PurchaseDetail> purDelEw = new EntityWrapper<>();
                purDelEw.setEntity(new PurchaseDetail());
                purDelEw.eq("purId", purchaseApply.getPurId());
                purDelEw.eq("maId", material.getMaId());
                PurchaseDetail purchaseDetailSearch = selectOne(purDelEw);
                if(purchaseDetailSearch != null){
                    //若原来有此条数据，则在原来的基础上添加
                    purchaseDetail.setPurdId(purchaseDetailSearch.getPurdId());
                    purchaseDetail.setPurdNum(purchaseDetail.getPurdNum() + purchaseDetailSearch.getPurdNum());
                    purchaseDetail.setPurdTotalPrice(purchaseDetail.getPurdNum() * material.getUnitPrice());
                    purchaseDetail.setUpdateDate(new Date());
                    purchaseDetail.setUpdateBy(curUser.getUsId());
                    purchaseDetail.setReqDate(new Date());
                    purchaseDetail.setReqPerson(purchaseApply.getPurPerson());
                    updateById(purchaseDetail);
                }else{
                    //若原来无此条数据，则重新添加
                    purchaseDetail.setPurdId(UUID.randomUUID().toString().replace("-",""));
                    purchaseDetail.setCreateBy(curUser.getUsId());
                    purchaseDetail.setCreateDate(new Date());
                    purchaseDetail.setPurId(purchaseApply.getPurId());
                    purchaseDetail.setMaId(material.getMaId());
                    purchaseDetail.setReqDate(new Date());
                    purchaseDetail.setReqPerson(purchaseApply.getPurPerson());
                    purchaseDetailMapper.insert(purchaseDetail);
                }
            }else{
                //更新操作
                purchaseDetail.setReqDate(new Date());
                purchaseDetail.setReqPerson(purchaseApply.getPurPerson());
                purchaseDetail.setUpdateBy(curUser.getUsId());
                purchaseDetail.setUpdateDate(new Date());
                updateById(purchaseDetail);
            }
        }
        return commonResult;
    }

    @Override
    public void saveConfirm(List<PurchaseDetailIn> purchaseDetailInList,String userId) throws Exception {
        // 当index==0时 对入库单号查询
        int index = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (PurchaseDetailIn pd:purchaseDetailInList){
            //保存请购申请清单表
            PurchaseDetail purchaseDetail = new PurchaseDetail();
            purchaseDetail.setPurdId(pd.getPurdId());
            purchaseDetail.setPurdDate(sdf.parse(pd.getPurdDate()));
            purchaseDetail.setPurdState(pd.getPurdState());
            purchaseDetail.setUpdateBy(userId);
            purchaseDetail.setUpdateDate(new Date());
            purchaseDetailMapper.updateById(purchaseDetail);
            //保存入库单
            iStoreService.savePutByLc(userId,pd,index,uuid);
            index ++;
        }
    }

    @Override
    public List<PurchaseDetail> getPurchaseDetails(Wrapper<PurchaseDetail> ew) {
        return purchaseDetailMapper.getPurchaseDetails(ew);
    }

    @Override
    public List<Map<String, Object>> getPurchaseDetailMaps(Wrapper<PurchaseDetail> ew) {
        return purchaseDetailMapper.getPurchaseDetailMaps(ew);
    }
}
